<?php

namespace app\agent\controller;

use app\agent\service\Channel as Service;
use app\model\AgentChannel;
use app\model\AgentServiceConfig;
use think\Request;
use think\facade\Db;

class Channel extends Controller
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * @api {POST} /agent/channel 渠道列表
     * @apiDescription 渠道列表
     * @apiName agentChannelList 渠道列表
     * @apiGroup Admin2_0_agent
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function index(Request $request)
    {
        $all = input('all', false);


        //添加渠道链接
        $query = AgentChannel::with('servDiscount')
            ->withJoin('template')
            ->withSearch(['template_id', 'name'], $request->all())
            ->where('agent_channel.agent_id', $this->agent['id'])
            ->order('agent_channel.id desc');


        if ($all == true) {
            $data = $query->select()->toArray();

        } else {
            $data = $query->paginate()->toArray();
        }


        // 根据模板状态，控制渠道是否启用
        $template = Db::name('template')
            ->column('status', 'id');
        foreach ($all == false ? $data['data'] : $data as $k => $v) {

            if ($v['state'] != 1) {
                continue;
            }

            if (!isset($template[$v['template_id']]) || $template[$v['template_id']] != 1) {
                $data['data'][$k]['state'] = 2;
            }
            $data['settle_type'] = $this->agent['settle_type'];
        }

        return success('', $data);
    }

    /**
     * @api {POST} /agent/channel/save 渠道保存
     * @apiDescription 渠道保存
     * @apiName agentChannelSave 渠道保存
     * @apiGroup Admin2_0_agent
     * @apiParam {Number} [id] 保存时候传递新建不传或者赋值0
     * @apiParam {String} name 渠道名称
     * @apiParam {String} remark 请填写渠道描述
     * @apiParam {Number} template_id 模板id
     * @apiParam {Object} config 渠道业务配置 key为业务serv_type ,对应value为数组格式,数组key为 channel_serv_discount 表字段--除了 时间外的
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function save(Request $request)
    {
        $id = $request->param('id', 0);
        // 数据表,字段名,排除ID,主键名
        $rules = [
            'name' => 'require|length:1,20|unique:agent_channel,name^is_deleted,' . $id,
            'remark' => 'require|length:1,255',
            'template_id' => 'require',
            'config' => 'require',
        ];
        $messages = [
            'name.require' => '请填写名称',
            'name.length' => '渠道名称不能超过 20 个字符',
            'name.unique' => '渠道名称已经存在',
            'remark.require' => '请填写渠道描述',
            'remark.length' => '备注不能超过 255 个字符',
            'template_id.require' => '请选择模板',
            'config.require' => '请填写模板信息',
        ];
        $param = $request->only(array_keys($rules));
        $param['is_deleted'] = 0;
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        $config = $param['config'];
        unset($param['config']);

        $res = Service::make()->channelSave($param, $config, $this->agent['id'], $id);
        if ($res['code']) {
            return fail($res['msg']);
        }

        return success();
    }

    /**
     * @api {POST} /agent/channel/delete 代理商渠道删除
     * @apiDescription 代理商渠道删除
     * @apiName agentChannelDelete 代理商渠道删除
     * @apiGroup Admin2_0_agent
     * @apiParam {Number} id id
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function delete()
    {
        if (!$id = $this->request->param('id')) {
            return fail('非法参数');
        }
        $agentChannel = AgentChannel::where('agent_id', $this->agent['id'])->find($id);
        if (!$agentChannel) {
            return fail('数组不存在');
        }
        if (AgentChannel::destroy($id)) {
            return success();
        }

        return fail();
    }


    /**
     * 设置订单入口显示状态
     */
    public function orderDisStatus(Request $request)
    {
        $rules = [
            'id'                   => 'require',
            'order_display_status' => 'require|in:1,2',
        ];
        $messages = [
            'id.require'                   => 'id不能为空',
            'order_display_status.require' => '订单入口显示状态不能为空',
            'order_display_status.in'      => '订单入口显示状态值只能是1或者2',
        ];
        $param = $request->only(array_keys($rules));
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        $info = AgentChannel::query()->where('id', $param['id'])->find();
        if (!$info) {
            return fail('设置失败');
        }
        $info->order_display_status = $param['order_display_status'];
        if ($info->save())
        {
            return success('设置成功');
        }
        return fail('设置失败');
    }
}
